import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import javax.swing.JOptionPane;

/**
 * The class provides functionalities for file I/O
 * 
 */
public class TextFileManager extends FileManager {
	
	private static int employeeId = 10000; 
	
	/**
	 * Construct a new TextFileManager object with the value of the passed in
	 * parameter
	 * 
	 * @param fileName
	 *            - the name of the file to operate on
	 */
	public TextFileManager(String fileName) {
		super(fileName);
	}


	/**
	 * Read an integer using the passed in scanner
	 * 
	 * @param scanner
	 *            - scanner to use
	 * @return the read integer
	 */
	protected int readInt(Scanner scanner) throws Exception {
		int i = scanner.nextInt();
		scanner.nextLine();
		return i;
	}

	/**
	 * Read a decimal number using the passed in scanner
	 * 
	 * @param scanner
	 *            - scanner to use
	 * @return the read decimal number
	 */
	protected double readDouble(Scanner scanner) throws Exception {
		return scanner.nextDouble();
	}

	/**
	 * Read a line using the passed in scanner
	 * 
	 * @param scanner
	 *            - scanner to use
	 * @return the read line
	 */
	protected String readLine(Scanner scanner) throws Exception {
		return scanner.nextLine();
	}

	/**
	 * Read a boolean value using the passed in parameter
	 * 
	 * @param scanner
	 *            - scanner to use
	 * @return the read boolean value
	 */
	protected boolean readBoolean(Scanner scanner) throws Exception {
		return scanner.nextBoolean();
	}

	//Load departments and employees from file into ArrayList. Return departments list
	public List loadData() throws SystemException, Exception{

		Scanner scanner = null;
		List<Employee> employees = null;
		List<Department> departments = null;
		int departmentsNum;
		
		File f = getFile();
		if(f.exists()){
			scanner = new Scanner(f);
			employees = new ArrayList<Employee>();
			departments = new ArrayList<Department>();
			
			//Read first line: number of departments
			departmentsNum = readInt(scanner);
			System.out.println("Number of Departments: "+ departmentsNum);
			
			//Loop to create a new departments and employees
			for(int i=0; i<departmentsNum; i++){
				String departmentName 	   = readLine(scanner);
				System.out.println("=========="+departmentName+(i+1)+"==========");
				String departmentLocation  = readLine(scanner);
				System.out.println("=========="+departmentLocation+"==========");
				int employeesNum	       = readInt(scanner);
				System.out.println("Number of employees: "+employeesNum);
				
				//Create a new department
				Department d = new Department(departmentName, departmentLocation);
				
				//Loop to get employee data
				for(int j=0; j<employeesNum; j++){
					System.out.println("==========Employee "+(j+1)+"==========");
					String firstName = readLine(scanner);
					System.out.println("First Name: "+firstName);
					String surname   = readLine(scanner);
					System.out.println("Surname: "+surname);
					String gender    = readLine(scanner);
					System.out.println("Gender : "+gender);
					String address   = readLine(scanner);
					System.out.println("Address: "+address);
					int payLevel     = readInt(scanner);
					if(firstName.length() < 1 || surname.length() < 1 || address.length() < 1 || gender.length()<1){
						throw new SystemException(SystemErrors.DATA_IS_BLANK);
					}
					if(payLevel<1 || payLevel>8){
						throw new SystemException(SystemErrors.UNDEFINED_PAYLEVEL);
					}
					System.out.println("Pay Level: "+payLevel);
					
					//Add employee to current department
					d.addEmployee(new Employee(firstName, surname, address, gender, employeeId, payLevel));
					//Increase employee ID
					employeeId++;
				}
				departments.add(d);
			}
			scanner.close();
		}
		
		return departments;
	}
	
	//Save payroll to text file
	@Override
	public void saveData(Collection objects) throws Exception {
		FileWriter fileWriter = new FileWriter(getFile());
		PrintWriter printWriter = new PrintWriter(fileWriter);
		
		//Sort departments alphabetically
		Collections.sort((List<Department>)objects);
		double totalCompany = 0;
		
		for(Department d : (List<Department>)objects){
			double totalDepartment = 0;
			printWriter.println("========= "+d+" =========");
			ArrayList<Employee> em = d.getEmployees();
			//Sort employees based on salary
			Collections.sort(em);
			for(Employee e : em){
				//Salary of each employee
				printWriter.println(e+": $"+(double)Math.round(e.getSalary()/26*100)/100);
				//Total amount the department has to pay
				totalDepartment += (double)Math.round(e.getSalary()/26*100)/100;
			}
			totalCompany += totalDepartment;
			printWriter.println("Total for "+d+": $"+(double)Math.round(totalDepartment*100)/100);
			printWriter.println("===========================================");
		}
		//Total amount the company has to pay
		printWriter.println("===========================================");
		printWriter.println("Total for company: $"+(double)Math.round(totalCompany*100)/100);
		printWriter.println("===========================================");
		printWriter.close();
		
	}


}
